
using Gradio.Net;

namespace GradioNetWebDemo
{
    public class Program
    {
        public static async Task Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            builder.Services.AddGradio();

            var app = builder.Build();

            app.UseGradio(await CreateBlocks());
            app.Run();
        }

        static async Task<Blocks> CreateBlocks()
        {
            using (var blocks = gr.Blocks())
            {
                gr.Markdown("Start typing below and then click **Run** to see the output.");
                Textbox input, output;
                using (gr.Row())
                {
                    input = gr.Textbox(placeholder: "What is your name?");
                    output = gr.Textbox();
                }
                var btn = gr.Button("Run");
                await btn.Click(fn: async (input) => gr.Output($"Welcome to Gradio.Net, {input.Data[0]}!"), inputs: new[] { input }, outputs: new[] { output });

                return blocks;
            }

            /*
            using (var blocks = gr.Blocks())
            {
                gr.Markdown("# Chatbot Demo");

                var chatbot = gr.Chatbot();
                var msg = gr.Textbox(placeholder: "Enter to Submit");
                await msg.Submit(streamingFn: (input) => Respond(Textbox.Payload(input.Data[0]), Chatbot.Payload(input.Data[1])),
                    inputs: new Component[] { msg, chatbot }, outputs: new Component[] { msg, chatbot });
                return blocks;
            }
            */
        }
        public static async IAsyncEnumerable<Output> Respond(string message, IList<ChatbotMessagePair> chatHistory)
        {
            chatHistory.Add(new ChatbotMessagePair(message, "You typed: "));

            for (int i = 0; i < message.Length; i++)
            {
                await Task.Delay(500);
                chatHistory.Last().AiMessage.TextMessage += message[i];

                yield return gr.Output("", chatHistory);
            }
        }

    }
}
